package com.quickstart.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quickstart.entity.User;
import com.quickstart.service.IUserService;
import com.quickstart.utils.ApiResponse;


@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/")
    public ApiResponse<User> addUser(@RequestBody @Valid User user) {
        boolean saved = userService.save(user);
        if (saved) {
            return new ApiResponse<>(200, "User added successfully", user);
        } else {
            return new ApiResponse<>(500, "Error adding user", null);
        }
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteUser(@PathVariable Long id) {
        boolean removed = userService.removeById(id);
        if (removed) {
            return new ApiResponse<>(200, "User deleted successfully", null);
        } else {
            return new ApiResponse<>(500, "Error deleting user", null);
        }
    }

    @PutMapping("/")
    public ApiResponse<User> updateUser(@RequestBody @Valid User user) {
        boolean updated = userService.updateById(user);
        if (updated) {
            return new ApiResponse<>(200, "User updated successfully", user);
        } else {
            return new ApiResponse<>(500, "Error updating user", null);
        }
    }

    @GetMapping("/{id}")
    public ApiResponse<User> getUserById(@PathVariable Long id) {
        User user = userService.getById(id);
        if (user != null) {
            return new ApiResponse<>(200, "User found", user);
        } else {
            return new ApiResponse<>(404, "User not found", null);
        }
    }


    @GetMapping
    public ApiResponse<Page<User>> getUsers(@RequestParam(value = "page", defaultValue = "1") int page,
                                             @RequestParam(value = "size", defaultValue = "10") int size) {
        Page<User> userPage = userService.selectUserPage(page, size);
        return new ApiResponse<>(200, "Users retrieved successfully", userPage);
    }
}
